﻿/*
Copyright (c) 2012 Vratislav Cermak (vratacermak@gmail.com)
 
This file is part of TeachMe Project. See http://code.google.com/p/teach-me for more information.
 
TeachMe is an open source project. Using of TeachMe is free of charge.
It is distributed under GNU General Public License version 3 (GPLv3).
GPLv3 can be found at http://www.gnu.org/licenses/gpl.html.
 
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

using System;
using System.Drawing;
using System.Linq;

namespace TeachMe.Application.Pexeso
{
    public class BoardGenerator
    {
        private readonly Random _rand = new Random(DateTime.Now.Millisecond);
        private readonly int _axisSize;
        private readonly bool[][] _board;

        public BoardGenerator(int axisSize)
        {
            _axisSize = axisSize;
            _board = new bool[_axisSize][];
            for (int idx = 0; idx < axisSize; idx++)
            {
                _board[idx] = new bool[axisSize];
            }
        }

        public Point Next()
        {
            // are we full?
            if (Full)
            {
                throw new InvalidOperationException();
            }

            int left, top;

            // get col where at least one row is not occupied
            do
            {
                left = _rand.Next(_axisSize);
            } while (_board[left].All(x => x));

            // get row
            do
            {
                top = _rand.Next(_axisSize);
            } while (_board[left][top]);

            _board[left][top] = true;

            return new Point(left, top);
        }

        public bool Full
        {
            get { return !_board.Any(x => x.Any(y => !y)); }
        }
    }
}
